package ru.aslanov.schedule.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.*;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.types.Side;
import com.smartgwt.client.types.TabBarControls;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;
import com.smartgwt.client.widgets.tab.events.TabSelectedEvent;
import com.smartgwt.client.widgets.tab.events.TabSelectedHandler;
import ru.aslanov.schedule.client.ds.SchedulesDS;
import ru.aslanov.schedule.client.i18n.I18nUtil;

/**
 * Created by IntelliJ IDEA.
 * Created: Nov 25, 2009 6:15:53 PM
 *
 * @author Sergey Aslanov
 */
public class Schedule implements EntryPoint {
    private static final String MAIN_TAB = "main";

    public void onModuleLoad() {
        ScheduleServices.App.getInstance().getUserData(new AsyncCallback<UserData>() {
            @Override
            public void onFailure(Throwable throwable) {
                SC.warn("Cannot load user information");
            }

            @Override
            public void onSuccess(UserData userData) {
                createMainPanel(userData);
            }
        });
    }

    private void createMainPanel(final UserData userData) {
        VLayout main = new VLayout();
        main.setWidth100();
        main.setHeight100();
        main.setLayoutMargin(5);

        final TabSet mainTabSet = new TabSet();
        mainTabSet.setTabBarPosition(Side.TOP);

        mainTabSet.setTabBarThickness(25);
        mainTabSet.setTabBarAlign(Side.LEFT);
        mainTabSet.setWidth100();
        mainTabSet.setHeight100();

        String lang = "<a href='?locale=en'>English</a>&nbsp;|&nbsp;<a href='?locale=ru'>Русский</a>";
        final Label userInfo = new Label(lang + "&nbsp;&nbsp;&nbsp;&nbsp;" + I18nUtil.cnt().hello() + ",&nbsp;" + userData.getEmail()
                + "&nbsp;[<a href='/logout'>" + I18nUtil.cnt().logout() + "</a>]");
        mainTabSet.setTabBarControls(TabBarControls.TAB_SCROLLER, TabBarControls.TAB_PICKER, userInfo);

        final Tab listTab = new Tab(I18nUtil.cnt().list());
        listTab.setID(MAIN_TAB);
        mainTabSet.addTab(listTab);

        SchedulesListPanel schedulesPane = new SchedulesListPanel(userData.isAdmin(), new SchedulesListPanel.ProcessRecordHandler() {
            @Override
            public void process(Record record) {
                final String scheduleKey = record.getAttribute("encodedKey");
                String name = record.getAttribute("name");
                if (name == null) {
                    name = scheduleKey;
                }
                openSchedule(mainTabSet, scheduleKey, userData);
            }
        });
        listTab.setPane(schedulesPane);

        if (userData.isAdmin()) {
            Tab adminTab = new Tab("Admin tools");
            mainTabSet.addTab(adminTab);
            adminTab.setPane(new AdminPanel());
        }

        main.addMember(mainTabSet);

        main.draw();

        onHistory(History.getToken(), mainTabSet, userData);

        History.addValueChangeHandler(new ValueChangeHandler<String>() {
            public void onValueChange(ValueChangeEvent<String> event) {
                String scheduleKey = event.getValue();
                onHistory(scheduleKey, mainTabSet, userData);
            }
        });

        mainTabSet.addTabSelectedHandler(new TabSelectedHandler() {
            @Override
            public void onTabSelected(TabSelectedEvent tabSelectedEvent) {
                final Tab tab = tabSelectedEvent.getTab();
                if (tab.getPane() instanceof SchedulePanel) {
                    History.newItem(((SchedulePanel)tab.getPane()).getScheduleKey());
                } else {
                    History.newItem(null);
                }
            }
        });
    }

    private void onHistory(String scheduleKey, TabSet mainTabSet, UserData user) {
        if (scheduleKey != null && scheduleKey.trim().length() != 0) {
            openSchedule(mainTabSet, scheduleKey, user);
        } else {
            mainTabSet.selectTab(MAIN_TAB);
        }
    }

    private void openSchedule(final TabSet mainTabSet, final String scheduleKey, final UserData user) {
        boolean found = false;
        for (Tab tab : mainTabSet.getTabs()) {
            if (tab.getPane() instanceof SchedulePanel) {
                SchedulePanel panel = (SchedulePanel) tab.getPane();
                if (panel.getScheduleKey().equals(scheduleKey)) {
                    mainTabSet.selectTab(tab);
                    found = true;
                    break;
                }
            }
        }
        if (!found) {
            SchedulesDS.getInstance().fetchData(new Criteria("encodedKey",scheduleKey), new DSCallback() {
                @Override
                public void execute(DSResponse dsResponse, Object o, DSRequest dsRequest) {
                    if (dsResponse.getStatus() == RPCResponse.STATUS_SUCCESS) {
                        final Record[] data = dsResponse.getData();
                        if (data.length == 1) {
                            final Record record = data[0];

                            ScheduleUser scheduleUser = new ScheduleUser(user, record);

                            final Canvas panel = new SchedulePanel(scheduleUser);
                            final String name = record.getAttribute("name");
                            Tab scheduleTab = new Tab(I18nUtil.cnt().schedule() + ": " + (name != null ? name : scheduleKey));
                            scheduleTab.setCanClose(true);
                            scheduleTab.setPane(panel);
                            mainTabSet.addTab(scheduleTab);
                            mainTabSet.selectTab(scheduleTab);
                        }
                    }
                }
            });
        }
    }


}
